<template>
  <a-divider
    v-if="nodeCandidateList?.length"
    class="flow-detail-form-title"
    orientation="left"
    orientation-margin="0px"
    style="font-size: 14px; font-weight: 700"
  >
    下一步表单接收人
  </a-divider>
  <a-form
    v-for="(form, index) in nodeCandidateList"
    :key="index"
    :ref="`formRef${index}`"
    v-bind="layout"
    :model="form"
    :rules="rules"
    class="form-excel-style"
  >
    <a-row>
      <a-col v-bind="colLayout.cols">
        <a-form-item name="nextNodeName" label="过程节点名称">
          <a-input :value="form.nextNodeName" disabled />
        </a-form-item>
      </a-col>
      <a-col v-bind="colLayout.cols">
        <a-form-item name="responsibleUnitId" label="责任单位/部门">
          <AvicCommonSelect
            v-model:value="form.responsibleUnitId"
            :default-show-value="form.responsibleUnitName"
            placeholder="请选择"
            type="deptSelect"
            :org-checkable="true"
            :disabled="readOnly"
            @callback="(values, records) => handleSelectUnit(values, records, form)"
          />
        </a-form-item>
      </a-col>
      <a-col v-bind="colLayout.cols">
        <a-form-item name="userId" label="责任人">
          <AvicCommonSelect
            v-model:value="form.userId"
            :default-show-value="form.userName"
            placeholder="请选择"
            type="userSelect"
            :disabled="readOnly"
            :default-org-id="form.orgId"
            :default-load-dept-id="form.orgType === 'dept' ? form.responsibleUnitId : ''"
            @callback="
              (value, selectedRows) => {
                form.userName = value.names;
                form.deptId = selectedRows[0]?.attributes?.deptid;
                form.deptName = selectedRows[0]?.attributes?.deptname;
              }
            "
          />
        </a-form-item>
      </a-col>
      <a-col v-bind="colLayout.cols">
        <a-form-item name="planCompleteTimeStr" label="计划完成时间">
          <a-date-picker
            v-model:value="form.planCompleteTimeStr"
            :disabled="readOnly"
            value-format="YYYY-MM-DD 00:00:00"
            format="YYYY-MM-DD"
          />
        </a-form-item>
      </a-col>
    </a-row>
  </a-form>
</template>
<script setup lang="ts">
import {
  getParentPIInstanceId,
  getParentPINextActivitys,
  getBpmPiInstanceCandidatesByInstanceId,
  saveNodeCandidate as bpmPiSaveNodeCandidate
} from '@/api/avic/bpmpi/BpmPiInstanceApi';
import { Dayjs } from 'dayjs';
const { proxy } = getCurrentInstance();
const props = defineProps({
  /**
   * 流程实例对象
   */
  bpmInstanceObject: {
    type: Object,
    required: true
  },
  /**
   * 按照流程节点控制权限
   */
  readOnly: {
    type: Boolean,
    default: false
  },
  /**
   * 保存节点处理人的API方法，需返回Promise
   */
  // eslint-disable-next-line vue/require-default-prop
  saveNodeCandidate: {
    type: [Function, null],
    requied: false,
    default: () => bpmPiSaveNodeCandidate
  }
});
const layout = {
  labelCol: { flex: '0 0 140px' },
  wrapperCol: { flex: '1 1 0' }
};
const colLayout = proxy.$colLayout4; // 调用布局公共方法

const checkPlanCompleteTime = async (_rule: Rule, value: Dayjs) => {
  if (props.readOnly) {
    return Promise.resolve();
  }
  if (proxy.$dayjs(value).isBefore(proxy.$dayjs().startOf('day'))) {
    return Promise.reject('计划完成时间应该晚于当前时间');
  }
  return Promise.resolve();
};
const rules: Record<string, Rule[]> = {
  responsibleUnitId: [{ required: true, message: '责任单位/部门不能为空', trigger: 'change' }],
  userId: [{ required: true, message: '责任人不能为空', trigger: 'change' }],
  planCompleteTimeStr: [
    { required: true, message: '计划完成时间不能为空', trigger: 'change' },
    { validator: checkPlanCompleteTime, trigger: 'change' }
  ]
};
const nodeCandidateList = ref([]);
const instanceId = ref('');
// 判断是否过程发起流程标记
const isPiStartFlow = ref(false);
// 提取配置项
const ACTIVITY_NAMES = ['piflow', 'pisubprocess'];
function isActivityNameMatch(activityName) {
  if (!activityName) return false;
  return ACTIVITY_NAMES.some((name) => activityName.includes(name));
}
/**
 * 根据流程实例Id获取过程实例Id
 */
function getBpmPiInstanceId() {
  return getParentPIInstanceId(props.bpmInstanceObject.bpmModel.entryId).then((res) => {
    // 后期将该组件提取到流程框架时使用，判断是否显示该组件
    if (isActivityNameMatch(res.data.activityName)) {
      isPiStartFlow.value = true;
    }
    instanceId.value = res.data.parentEntryId;
  });
}
const nodeCandidateConfigList = ref([]);
/**
 * 根据过程实例Id获取过程实例节点配置
 */
function loadNodeCandidateConfigList() {
  return getBpmPiInstanceCandidatesByInstanceId(instanceId.value).then((res) => {
    nodeCandidateConfigList.value = res.data || [];
  });
}

const nextStepNodes = ref([]);
/**
 * 根据过程实例Id获取下一步过程节点集合
 */
function loadParentPINextActivitys() {
  return getParentPINextActivitys(props.bpmInstanceObject.bpmModel.entryId).then((res) => {
    nextStepNodes.value = res.data?.nextActivitys || [];
    instanceId.value = res.data.processInstanceId;
  });
}

function loadProcessInstanceCandidate() {
  nodeCandidateList.value = nextStepNodes.value
    .map((node) => {
      const candidate = nodeCandidateConfigList.value.find(
        (nodeUser) => nodeUser.nodeId === node.activityName && nodeUser.instanceId === instanceId.value
      );
      return {
        nodeId: node.activityName,
        nextNodeName: node.activityAlias,
        userId: candidate?.userId || '',
        userName: candidate?.userName || '',
        orgType: candidate?.orgType || '',
        orgId: candidate?.orgId || '',
        deptId: candidate?.deptId || '',
        deptName: candidate?.deptName || '',
        taskName: candidate?.taskName || node.activityAlias,
        // 计划完成时间
        planCompleteTimeStr: candidate?.planCompleteTime ? proxy.$dayjs(candidate.planCompleteTime).format('YYYY-MM-DD 00:00:00') : '',
        // 责任单位id
        responsibleUnitId: candidate?.responsibleUnitId || '',
        // 责任单位名称
        responsibleUnitName: candidate?.responsibleUnitName || ''
      };
    })
    .filter((item) => item);
}
function handleSelectUnit(value, records, form) {
  if (!records?.length) {
    form.orgId = '';
    form.responsibleUnitName = '';
    return;
  }
  form.orgType = records[0]?.nodeType;
  if (records[0]?.nodeType !== 'org') {
    form.orgId = records[0].attributes?.ownOrgId;
  } else {
    form.orgId = value.ids;
  }
  form.responsibleUnitName = value.names;
}
defineExpose({ saveConfig });
function saveConfig() {
  if (props.readOnly) {
    return Promise.resolve();
  }
  return new Promise((resolve, reject) => {
    const promises = [];
    nodeCandidateList.value?.forEach((item, index) => {
      promises.push(proxy.$refs[`formRef${index}`][0].validate());
    });
    Promise.all(promises)
      .then(() => {
        const requestPromises = [];
        nodeCandidateList.value?.forEach((item) => {
          requestPromises.push(
            props.saveNodeCandidate({
              ...item,
              instanceId: instanceId.value
            })
          );
        });
        Promise.all(requestPromises)
          .then((res) => {
            // proxy.$message.success('保存成功!');
            resolve(res);
          })
          .catch((error) => {
            reject(error);
          });
      })
      .catch((error) => {
        proxy.$message.error('请完善下一步表单接收人信息!');
        reject(error);
      });
  });
}
onMounted(() => {
  // loadProcessInstance();
  getBpmPiInstanceId().then(() => {
    if (isPiStartFlow.value) {
      const promises = [loadNodeCandidateConfigList(), loadParentPINextActivitys()];
      Promise.allSettled(promises).then(() => {
        loadProcessInstanceCandidate();
      });
    }
  });
});
</script>
<style lang="less" scoped>
.process-config-tabs {
  height: 100%;
  :deep(.ant-tabs-tab),
  :deep(.ant-tabs-content-holder),
  :deep(.ant-tabs-content) {
    height: 100%;
  }
  :deep(.ant-tabs-content) {
    padding-top: 4px;
  }
  .process-config-tab-user,
  .process-config-tab-fork {
    height: 100%;
    :deep(.advanced-table) {
      height: 100%;
    }
  }
}

.flow-detail-form-title {
  margin-top: 0;
  margin-bottom: 8px;
  height: 26px;
  &.ant-divider-with-text-left::after {
    transform: none;
  }
}
</style>
